package org.sws.trigger.job;

import cn.hutool.core.collection.CollectionUtil;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.sws.domain.activity.model.valobj.ActivitySkuStockKeyVO;
import org.sws.domain.activity.service.quota.IActivitySkuStockService;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @Author sws
 * @Date 2025/3/19
 * @description: 更新sku库存
 */
@Slf4j
@Component
public class UpdateSkuStockJob {
    @Resource
    private IActivitySkuStockService skuStock;
    @Resource
    private ThreadPoolExecutor executor;
    @Resource
    private RedissonClient redissonClient;
    @Scheduled(cron = "0/5 * * * * ?")
    public void exec(){
        RLock lock = redissonClient.getLock("big-market-UpdateActivitySkuStockJob");
        boolean isLocked = false;
        try {
            isLocked = lock.tryLock(3, 0, TimeUnit.SECONDS);
            if (!isLocked){
                return;
            }
            // 查询有效活动的sku列表
            List<Long> skus = skuStock.querySkuList();
            if(CollectionUtil.isEmpty(skus)){
                return;
            }
            for(Long sku : skus){
                executor.execute(() -> {
                    ActivitySkuStockKeyVO activitySkuStockKeyVO = null;
                    try {
                        activitySkuStockKeyVO = skuStock.takeQueueValue(sku);
                    } catch (InterruptedException e) {
                        log.error("定时任务，更新活动sku库存失败 sku: {}", sku);
                    }
                    if(null == activitySkuStockKeyVO){
                        return;
                    }
                    skuStock.updateActivitySkuStock(activitySkuStockKeyVO.getSku());
                    log.info("定时任务，更新活动sku库存 完成 sku:{} activityId:{}", activitySkuStockKeyVO.getSku(), activitySkuStockKeyVO.getActivityId());
                });
            }
        } catch (Exception e) {
            log.error("定时任务，更新sku消耗库存失败", e);
        }finally {
            if (isLocked) {
                lock.unlock();
            }
        }
    }
}
